package server.logger;

import server.Container;
import server.Logger;

import java.io.CharArrayWriter;
import java.io.PrintWriter;
/*
日志记录器基类,实现了除具体打印位置的log(String message);外的所有方法
*/
/*
2023/2/8 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public abstract class LoggerBase implements Logger {

    //日志打印器所属的容器
    protected Container container = null;
    protected int debug = 0;
    protected static final String info = "server.logger.LoggerBase/1.0";
    //日志打印级别
    protected int verbosity = ERROR;

    //getter-----------------------------------------------------------------------------
    public int getDebug() {
        return debug;
    }
    //setter-----------------------------------------------------------------------------
    public void setDebug(int debug) {
        this.debug = debug;
    }
    public void setVerbosityLevel(String verbosity) {
        if ("FATAL".equalsIgnoreCase(verbosity))
            this.verbosity = FATAL;
        else if ("ERROR".equalsIgnoreCase(verbosity))
            this.verbosity = ERROR;
        else if ("WARNING".equalsIgnoreCase(verbosity))
            this.verbosity = WARNING;
        else if ("INFORMATION".equalsIgnoreCase(verbosity))
            this.verbosity = INFORMATION;
        else if ("DEBUG".equalsIgnoreCase(verbosity))
            this.verbosity = DEBUG;
    }
    //实现Logger接口-----------------------------------------------------------------------------
    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }

    @Override
    public String getInfo() {
        return info;
    }

    @Override
    public int getVerbosity() {
        return verbosity;
    }

    @Override
    public void setVerbosity(int verbosity) {
        this.verbosity = verbosity;
    }

    @Override
    public abstract void log(String message);

    @Override
    public void log(Exception exception, String msg) {
        log(msg, exception);
    }

    @Override
    public void log(String message, Throwable throwable) {
        CharArrayWriter buffer = new CharArrayWriter();
        PrintWriter writer = new PrintWriter(buffer);
        writer.println(message);
        throwable.printStackTrace(writer);
        log(buffer.toString());
    }

    @Override
    public void log(String message, int verbosity) {
        if (verbosity <= this.verbosity)
            log(message);
    }

    @Override
    public void log(String message, Throwable throwable, int verbosity) {
        if (verbosity <= this.verbosity) {
            log(message, throwable);
        }
    }
}
